package cn.web.servlet;

import cn.Dao.UserDao;
import cn.domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet( "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        User loginUser = new User();
        // 以下这种写法太繁琐，需要逐个获取key 对应的value new一个实体类，再把value赋进去
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        loginUser.setUsername(username);
//        loginUser.setPassowrd(password);
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.populate(loginUser,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        UserDao userDao = new UserDao();
        User user1 = userDao.login(loginUser);
        if (user1 == null){
            request.getRequestDispatcher("/failServlet").forward(request,response);
        }else {
            request.setAttribute("user",user1);
            request.getRequestDispatcher("/successServlet").forward(request,response);
        }


    }
}
/*
beanutils工具类，简化数据封装
 */